// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database();
const _ = db.command;
const $ = db.command.aggregate;

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let openid = wxContext.OPENID;
  let limit_num = event.limit;
  let skip_num = event.skip;
  let res = new Object();
  let card_info = await db.collection('ops_card').where({
    Issuer_openid: openid,
  }).get();
  if (card_info.data.length == 0) {
    res.deliver_length = 0;
    res.deliver_list = [];
  } else {
    let id_array = [];
    for (i = 0; i < card_info.data.length; i++) {
      id_array[i] = card_info.data[i]._id;
    }
    let deliver_length = await db.collection('ops_order').where({
      card_id: _.in(id_array),
      status: 2
    }).count();
    if (deliver_length.total != 0) {
      let deliver_list = await db.collection('ops_order').aggregate().sort({
        update_time: -1
      }).match({
        card_id: _.in(id_array),
        status: _.gt(1)
      }).lookup({
        from: 'ops_goods',
        localField: 'goods_id',
        foreignField: '_id',
        as: 'goodsList',
      }).replaceRoot({
        newRoot: $.mergeObjects([$.arrayElemAt(['$goodsList', 0]), '$$ROOT'])
      }).project({
        goods_explain: 0,
        card_id: 0,
        goods_id: 0,
        goods_url: 0,
        number: 0,
        specs: 0,
        update_time: 0,
        user_delivery_date: 0,
        user_openid: 0,
        goodsList: 0
      }).limit(limit_num).skip(skip_num).end();
      res.deliver_length = deliver_length.total;
      res.deliver_list = deliver_list.list;
    } else {
      res.deliver_length = 0;
      res.deliver_list = [];
    }
  }
  return res;
}